package com.ts.view;

import java.util.ArrayList;
import java.util.List;

import com.rio.core.L;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * 
 * @author rio
 *
 */
public class SercetView extends View{
	
	private boolean isRunning;
	
	private static final long TIMEOUT = 1000;
	
	private int mCount ;
	
	private List<Point> mContent;
	
	private OnToggleListener mOnToggleListener;
	
	private static final int SIZE = 4;
	
	public SercetView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mCount = 0;
		mContent = new ArrayList<SercetView.Point>(SIZE);
	}

	
	public void setOnToggleListener(OnToggleListener listener) {
		this.mOnToggleListener = listener;
	}


	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if(mOnToggleListener != null && event.getAction() == MotionEvent.ACTION_DOWN){
			
			if(!isRunning){
				isRunning =  true;				
				new TimeThread().start();
			}
			if(isRunning){
				
				mCount++;
				mContent.add(new Point(event.getX(), event.getY()));
				
				if(mCount == SIZE){
					mCount = 0;
					if(toggle())mOnToggleListener.onToggle();
					mContent.clear();
				}
			}
			
			
		}
		return true;
	}
	
	private class TimeThread extends Thread{

		@Override
		public void run() {
			try {
				Thread.sleep(TIMEOUT);
			} catch (InterruptedException e) {

			}finally{
				if(isRunning){
					isRunning = false;					
				}
				mCount = 0;
			}
			
		}
		
	}
	
	private class Point{
		
		float x;
		float y;
		public Point(float x, float y) {
			super();
			this.x = x;
			this.y = y;
		}		
	}

	
	public interface OnToggleListener{
		
		public void onToggle();
		
	}
	
	
	private boolean toggle(){
		Point p1 = mContent.get(0);
		Point p2 = mContent.get(1);
		Point p3 = mContent.get(2);
		Point p4 = mContent.get(3);
		float x = (p1.x + p2.x)/2;
		float y = (p3.y + p4.y)/2;
		if(p3.x < x && p4.x > x && p1.y < y && p2.y > y ){
			return true;
		}
		
		return false;		
		
	}
	
}
